package com.atguigu.lease.web.app.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.CodeUtils;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.mapper.UserInfoMapper;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.SmsService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SmsService smsService;

    /**
     * 获取短信验证码
     * @param phone
     */
    @Override
    public void getCode(String phone) {

        //判断手机号是否为空
        if (!StringUtils.hasText(phone)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }

        String code = CodeUtils.getRandomCode(6);

        String key = RedisConstant.APP_LOGIN_PREFIX + phone;

        Boolean hasKey = stringRedisTemplate.hasKey(key);

        if (hasKey){
            //获取键的剩余过期时间
            Long expire = stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);

            if (RedisConstant.APP_LOGIN_CODE_TTL_SEC - expire < RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC){
                //发送验证码过度频繁
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }

        smsService.SendCode(phone,code);

        stringRedisTemplate.opsForValue().set(key,code,RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);

    }


    /**
     *  登录
     * @param loginVo
     * @return
     */
    @Override
    public String login(LoginVo loginVo) {

        if (loginVo.getPhone() ==null){

            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }

        if (loginVo.getCode() ==null){

            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }

        String key = RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone();

        String code = stringRedisTemplate.opsForValue().get(key);
        if (code == null){

            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }

        if (! loginVo.getCode().equals(code)){

            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }

        //根据`phone`从数据库中查询用户信息
        LambdaQueryWrapper<UserInfo> userInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userInfoLambdaQueryWrapper.eq(UserInfo::getPhone,loginVo.getPhone());

        UserInfo userInfo = userInfoMapper.selectOne(userInfoLambdaQueryWrapper);

        //判断用户是否为新用户 或 被禁用
        if (userInfo == null){

            //进行注册
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname("用户:"+loginVo.getPhone().substring(7));

            userInfoMapper.insert(userInfo);
        }else {

            //判断是否被禁用
            if (userInfo.getStatus().equals(BaseStatus.DISABLE)){
                throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
            }

        }

        return JwtUtil.createToken(userInfo.getId(),userInfo.getPhone());
    }

    /**
     * 获取登录用户信息
     * @param userId
     * @return
     */
    @Override
    public UserInfoVo getLoginUserById(Long userId) {

        UserInfo userInfo = userInfoMapper.selectById(userId);

        return new UserInfoVo(userInfo.getNickname(),userInfo.getAvatarUrl());
    }
}
